#include "SaveThread.h"
#include <QtConcurrent>
#include <string.h>
#include<winsock2.h>
#include <limits>

// #pragma comment(lib, "Ws2_32")

void SaveThread::udpDataSave(const QString &filePath,bool fileDivisionFlag,int fileDivisionSize)
{
    auto openNewFile = [=]{
        QDateTime dateTime= QDateTime::currentDateTime();//获取系统当前的时间
        QString fileName = filePath + dateTime .toString("yyyy-MM-dd_hh-mm-ss") + "rcvFile.bin";
        return QFile(fileName);
    };

    auto saveOneFile = [=](size_t maxLength){
        auto file = openNewFile();

        while (!stopFlag && ((size_t)file.size() < maxLength)) {
            if (!file.open(QIODevice::Append)) {
                qDebug() << "open file failed";
                return;
            }

            size_t maxNumber = maxLength - file.size();

            std::vector<char> data;

            while (!dataTemp->empty() && !stopFlag && (data.size() < maxNumber)) {
                // 加锁
                mutex.lock();
                data.push_back(dataTemp->front());
                dataTemp->pop();
                mutex.unlock();
            }

            file.write(data.data(), data.size());

            file.close();
        }
    };

    auto dataSaveThread = QtConcurrent::run([=](){            //dataSaveThread 没有实际作用，屏蔽warning
        qDebug() << "fileSave  ThreadID:"<<QThread::currentThreadId();
        //一级循环负责文件切割
        while (!stopFlag) {
            size_t maxLength = fileDivisionFlag ? fileDivisionSize *1024*1024*1024 : std::numeric_limits<size_t>::max();
            saveOneFile(maxLength);
        }
    });
}
